package com.mjk.common.web.getway.restful.interceptor.type.commons.impl;

import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.tools.interceptor.InterceptorChain;
import com.mjk.common.util.MapUtils;
import com.mjk.common.web.getway.constns.GetwayConsts;
import com.mjk.common.web.getway.restful.interceptor.GetWayInterceptorReq;
import com.mjk.common.web.getway.restful.interceptor.annotation.BeeGetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptorType;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Timer;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 指标记录收集 用于记录接口的请求 和 耗时等相关信息
 */
@BeeGetWayInterceptor(value=4,interceptorType={GetWayInterceptorType.ALL})
public class GetWayMetricsInterceptor implements GetWayInterceptor {
    @Autowired
    private MeterRegistry registry;
    @Override
    public BeeResponse interceptor(GetWayInterceptorReq request, InterceptorChain<GetWayInterceptorReq, BeeResponse> next) {
        // 记录请求时间
        List<Tag> tags = getTags(request);
        Timer.Sample timerSample = Timer.start(registry);
        Counter counter = registry.counter( "bee.requests.total",  tags);
        counter.increment();
        BeeResponse rsp = next.proceed(request);
        Timer timer = registry.timer( "bee.responseTime",tags);
        timerSample.stop(timer);
        return rsp;
    }

    private List<Tag> getTags(GetWayInterceptorReq request) {
        List<Tag> tags = new ArrayList<>();
        String proto = MapUtils.getString(request.getRestfulParams(),GetwayConsts.PROTOCOL);
        String work = MapUtils.getString(request.getRestfulParams(), GetwayConsts.INSTANCE);
        String method = MapUtils.getString(request.getParams(),GetwayConsts.METHOD);
        Tag paramTag = Tag.of("url", "ld/"+proto+"/v1/"+work+"?method="+method);
        tags.add(paramTag);
        return tags;
    }
}
